class V1::ProductAs < Grape::API
  resources :product_as do
    desc '获得指定产品的内容'
    get ':id', jbuilder: 'product_a' do
      @product_a = ProductA.find(params[:id])
    end

    desc '创建产品'
    params do
      requires :name, type: String
      optional :access_token, type: String
    end
    post do
      guard!
      args = ActionController::Parameters.new(params.slice(:name, :summary, :published_at, :url, :category)).permit!
      @product_a = ProductA.new(args)
      if @product_a.save
        return { product_a: @product_a }
      else
        error!({ error: 'can not created', message: '创建失败' }, 400)
      end
    end

    desc '搜索产品'
    params do
      requires :name, type: String
    end
    get do
      products = ProductA.where('name like ?', "%#{params[:name]}%")
      return products.map{|p| {name: p.name, url: Rails.application.routes.url_helpers.edit_admin_product_a_url(host: 'http://innoawards.geekpark.net', id: p.id)} }
    end
  end
end
